<?php
require_once('TVB/PWORKS/mvc/IFilter.iface.php');
require_once('TVB/PWORKS/mvc/IAction.iface.php');
require_once('TVB/PWORKS/message/Message.class.php');

class CommonFilter implements IFilter {
	public function before(IAction &$action) {

		try
		{
			$userId = $this->checkAuth($action);
			$action->setData('username', $userId);
			$action->setData('login', ($userId != 'tvb'));

			$cate   =   new cpl_category();
			$action->setData("rootcategory",$cate->getSubCategorys(0));
			$action->setData("frontview", $this->getFindFrontView());
			$action->setData('unpublish', $this->checkPublish());
		}
		catch(Exception $e)
		{
			return null;
		}

		return null;
	}

	public function after(IAction &$action) {

		$rs = $action->getResult();
		$rsType = $action->getConfig()->results[$rs]->type;
		if('redirect' == $rsType){
			$action->removeData('rootcategory');
			$action->removeData('frontview');
			$action->removeData('username');
			$action->removeData('login');
			$action->removeData('_gn');
			$action->removeData('_ug');
			$action->removeData('_up');
			$action->removeData('_g');
		}

		return null;
	}

	private function getFindFrontView()
	{
		$array  =   Model::parseFindRelation();
		$tmp    =   array();

		if (is_array($array))
		{
			foreach ($array as  $key    =>  $value)
			{
				$tmp[$key]  =   $value['frontView'];
			}
		}
		return  $tmp;
	}

	private function checkPublish()
	{
		if (empty($_REQUEST['unpublish']))  return  0;
		return  1;
	}

	private function checkAuth(IAction $action)
	{
		$userId = TVBGetAuthUserFromCookie();

		#testing 
		if(isset($_REQUEST['pt'])){
			$userId = 'vanni.fan@achievo.com';
			setcookie('test_permission',$userId,time()+3600,'/');
		}
		if(isset($_REQUEST['cpt'])){
			setcookie('test_permission','',time()-3600,'/');
		}
		if(isset($_COOKIE['test_permission'])){
			$userId = $_COOKIE['test_permission'];
		}

		if ($userId == FALSE) {

			$myUrl = ($_SERVER['REQUEST_URI']== "/" ) ? (AC::PDES_BASE_URL."pms_task.html") : (rtrim(AC::PDES_BASE_URL,'/').$_SERVER['REQUEST_URI']);
			$myUrl = urlencode($myUrl);
			$url = AC::AUTH_BASE_URL."login.php?destUrl={$myUrl}";
			header("Location: $url");
			exit;
		}else{

			// get system all permissions
			permission::initPermission();
			$all_permissions  = permission::getPermission();


			// get user permissions 
			$permission = Model::selectBySql('select permissions,g.system_label from user u inner join user_group g on u.user_group_id=g.id where u.system_label=:user',array(':user'=>$userId));
			if(!$permission){
				error_log("Access Denied!");
				exit('Access Denied!');
			}
			$action->setData('_gn',$permission[0]['system_label']);
			$permission = json_decode($permission[0]['permissions'],1);
			$permission = Model::selectBySql('select system_label from permission where id in('.implode(',',$permission).')');
			$user_permissions = array();
			$permission_group = array();
			foreach($permission as $_p){
				array_splice($user_permissions, 0, 0, $all_permissions[$_p['system_label']]);
				$permission_group[] = $_p['system_label'];
			}
			$user_permissions = array_values(array_unique($user_permissions));

			// get current action permissions
			$action->setData('_ug',array_fill_keys(array_values($permission_group),true));
			$current_permission = $action->getPermissionItems();
			$action_permission_group = $action->getData();
			$action_permission_group = $action_permission_group['_g'];
			// check permission
			#echo "<!-- ";
			#echo get_class($action);
			#print_r($current_permission);
			#print_r($permission_group);
			#echo " -->";
			$cpl  = array(); // current permission list
			foreach($permission_group as $group){
				$cpl = array_merge($cpl,$current_permission[$group]);
				$action_permission_group[$group] = true;
			}
			if(empty($cpl)){
				$msg = 'No Permission In "'.implode(',',$permission_group).'" Group!';
				error_log($msg);
				exit($msg);
			}
			foreach($cpl as $one){
				if(!in_array($one,$user_permissions)){
					$msg = 'Group:"'. implode(',',$permission_group) . '" No '. $one." Permission!";
					error_log($msg);
					exit($msg);
				}
			}

			$action->setData('_g',$action_permission_group);
			$action->setData('_up',$cpl);
			#error_log("===== end =====");
			#error_log("=====current_permission ".print_r($current_permission,1)." ====user_permission ". print_r($user_permissions,1). " === permission_group ".print_r($permission_group,1). "===");
		}

		return $userId;
	}

}
?>
